package cn.wolfcode.shop.cloud.resolver;

import cn.wolfcode.shop.cloud.annotation.UserParam;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import cn.wolfcode.shop.cloud.util.MemberKeyPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;


public class UserResolveArgument implements HandlerMethodArgumentResolver {
    @Autowired
    private RedisService redisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
   //设置支持的类型,判断返回的类型是不是user类型
        return methodParameter.getParameterType()== User.class
                && methodParameter.hasParameterAnnotation(UserParam.class);

    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String token = CookieUtil.getCookieVal((HttpServletRequest) nativeWebRequest.getNativeRequest(), "userToken");
        User user = redisService.get(MemberKeyPrefix.USER_TOKEN, token, User.class);
        return user;

    }


}
